const articleRepository = require('../repositories/articleRepositories')

class ArticleService {
  // 提取通用的响应处理函数
  handleResponse(data, error, notFoundMessage = '文章未找到') {
    if (error) {
      return {
        code: 1,
        msg: error.message,
        statusCode: error.statusCode || 500,
      };
    }
    if (!data) {
      return {
        code: 1,
        msg: notFoundMessage,
        statusCode: 404,
      };
    }
    return {
      code: 0,
      msg: data,
    }
  }

  async getAllArticles() {
    try {
      const articles = await articleRepository.getAllArticles()
      return this.handleResponse(articles)
    } catch (error) {
      return this.handleResponse(null, error)
    }
  }

  async getArticleById(id) {
    try {
      const article = await articleRepository.findById(id)
      return this.handleResponse(article)
    } catch (error) {
      return this.handleResponse(null, error)
    }
  }

  async createArticle(articleData) {
    try {
      const newArticle = await articleRepository.create(articleData)
      return this.handleResponse(newArticle);
    } catch (error) {
      error.statusCode = 400 // 设置特定的状态码
      return this.handleResponse(null, error)
    }
  }

  async updateArticle(id, articleData) {
    try {
      const updatedArticle = await articleRepository.update(id, articleData)
      return this.handleResponse(updatedArticle)
    } catch (error) {
      error.statusCode = 400 // 设置特定的状态码
      return this.handleResponse(null, error)
    }
  }

  async delArticleById(id) {
    try {
      const result = await articleRepository.delArticleById(id)
      if (result) {
        return this.handleResponse('文章删除成功')
      } else {
        return this.handleResponse(null, null, '文章未找到')
      }
    } catch (error) {
      return this.handleResponse(null, error)
    }
  }
}

module.exports = new ArticleService()